<template>
  <el-row :gutter="20">
    <el-col :span="24">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="充值卡号">
          <el-input v-model="formInline.code"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formInline.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOption"
              :key="item.key"
              :label="item.value"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期结束时间">
            <el-date-picker
              v-model="date"
              type="datetimerange"
              start-placeholder="开始日期"
              @change="changeDate"
              end-placeholder="结束日期" >
            </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-col :span="24" style="text-align: left">
      <el-button><router-link :to="{path:'/manage/rechargecardinfo'}"> 充值卡制作</router-link></el-button>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <!-- <el-table-column type="selection"> </el-table-column> -->
        <el-table-column prop="id" label="id"  width="100" ></el-table-column>
        <el-table-column prop="username"  label="用户名"  width="150"></el-table-column>

        <el-table-column label="状态" width="70">
          <template slot-scope="scope">{{ scope.row.status|status }}</template>
        </el-table-column>
        <el-table-column prop="code" label="卡号" width="270">
        </el-table-column>
         <el-table-column label="充值时间" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.useTime|dateFormat }}</template>
        </el-table-column>
        <!-- <el-table-column prop="validityStart" label="有效期开始" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.validityStart*1000|dateFormat }}</template>
        </el-table-column>  -->
        <el-table-column prop="validityEnd" label="有效期结束" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.validityEnd*1000|dateFormat }}</template>
        </el-table-column>
        <el-table-column   label="充值卡类型" show-overflow-tooltip>
           <template slot-scope="scope">{{ scope.row.validity|formatCycle}}&nbsp;&nbsp;({{scope.row.validity}}秒)</template>
        </el-table-column>
        <el-table-column label="创建时间" >
          <template slot-scope="scope">{{ scope.row.createTime|dateFormat }}</template>
        </el-table-column>
        <el-table-column  fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.status" @click="handleClick(scope.row.code)" type="text" size="small">  充值 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo.currentPage"
      :page-sizes="[10,20,30,40,50]"
      :page-size="pageInfo.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total">
    </el-pagination>

    <el-dialog title="代充值" :visible.sync="dialogFormVisible">
        <el-form :model="form" ref="addForm">
          <el-form-item label="请添加用户" label-width="100px">
            <!-- <el-select v-model="form.userId" placeholder="请选择" style="width:80%">
              <el-option
                v-for="item in userOption"
                :key="item.id"
                :label="item.username"
                :value="item.id">
              </el-option>
            </el-select>  -->
             <el-input v-model="form.userId" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="addInfo()">充 值</el-button>
        </div>
      </el-dialog>

    </el-col>
  </el-row>
</template>
<script>
import store from '@/store'
import { cardList,recharge} from '@/api/service'
import {fieldMap ,publicFilter} from '@/utils/showMap'
export default {
  data() {
    return {
      dialogFormVisible:false,
      userOption:[],
      date:'',
      statusOption:fieldMap.card_status,
      formInline: { //查询条件表单
        code: "",
        status: "",
        useBeginTime: "",
        useEndTime: "",
      },
      pageInfo:{
          currentPage: 1,
          size:15,
          total:0,
      },
      form:{
        userId:'',
      },
      cardId:'',
      tableData: [],
      multipleSelection: [],
    };
  },
   filters: {
    status: value=>publicFilter(fieldMap.card_status,String(value)),
    dateFormat:(args)=>{
          let fmt="YYYY-mm-dd HH:MM:SS"
          let ret;
          if(args){
            let  date=new Date(args)
               const opt = {
              "Y+": date.getFullYear().toString(),        // 年
              "m+": (date.getMonth() + 1).toString(),     // 月
              "d+": date.getDate().toString(),            // 日
              "H+": date.getHours().toString(),           // 时
              "M+": date.getMinutes().toString(),         // 分
              "S+": date.getSeconds().toString()          // 秒
          };
          for (let k in opt) {
              ret = new RegExp("(" + k + ")").exec(fmt);
              if (ret) {
                  fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
              };
          };
          return fmt;
          }else{
            return "";
          }

      },
    formatCycle:value=>{//86400
      if(value==604800){
        return "周卡";
      }else if(value==1296000){
        return "半月卡";
      }else if(value==2678400){
        return "月卡";
      }else if(value==8035200){
        return "季度卡";
      }else if(value==15984000){
        return "半年卡";
      }else if(value==31536000){
        return "年卡";
      }else{
        return "其他";
      }
    }
  },
  mounted(){
    this.search();
    store.dispatch('user/getUserList',{page:1,size:9999999}).then(res=>{
          this.userOption=res.data.content;
     })
  },
  methods: {
    dateFormats(args){
          let fmt="YYYY-mm-dd HH:MM:SS"
          let ret;
          if(args){
            let  date=new Date(args)
               const opt = {
              "Y+": date.getFullYear().toString(),        // 年
              "m+": (date.getMonth() + 1).toString(),     // 月
              "d+": date.getDate().toString(),            // 日
              "H+": date.getHours().toString(),           // 时
              "M+": date.getMinutes().toString(),         // 分
              "S+": date.getSeconds().toString()          // 秒
          };
          for (let k in opt) {
              ret = new RegExp("(" + k + ")").exec(fmt);
              if (ret) {
                  fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
              };
          };
          return fmt;
          }else{
            return "";
          }

      },
     addInfo(){
        let data={ code: this.cardId ,username:this.form.userId}
        recharge(data).then((res) => {
            this.formInline.code="";
            // Message({
            //   message: res.msg || "充值成功",
            //   type: "success",
            //   duration: 3 * 1000,
            // });
             this.$message({
              message: res.msg || "充值成功",
              type: 'success'
            });
            this.dialogFormVisible=false;
            this.search();
          });
    },
    cancel(){
      this.dialogFormVisible=false;
      this.$refs.addForm.resetFields();
    },
     handleClick(args) {
        this.dialogFormVisible=true;
        this.cardId=args;
    },
    search(){
          cardList({page:this.pageInfo.currentPage,size:this.pageInfo.size,...this.formInline}).then(res=>{
          this.tableData=res.data.content;
          this.pageInfo.currentPage=res.data.page;
          this.pageInfo.total=res.data.total;
          this.pageInfo.size=res.data.size;
     })
    },
    onSubmit() {
      console.log("submit!");
      this.search();
    },
     changeDate(){
       if(this.date){
          let a=this.date[0];
          let b=this.date[1];
      // console.log();

       this.formInline.useBeginTime=a.getTime();
       this.formInline.useEndTime=b.getTime();
       }else{
       this.formInline.useBeginTime="";
       this.formInline.useEndTime="";
       }

    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

     handleSizeChange(val) {
       this.pageInfo.size=val;
      this.search();
      },
      handleCurrentChange(val) {
         this.pageInfo.currentPage=val;
        this.search();
      }
  },
};
</script>
<style lang="less" scoped>
.demo-form-inline {
  text-align: left;
}
.pagination{
  margin:15px auto;
}
</style>
